/*
 * Created on Jun 14, 2005
 *
 */
package com.erclab.internal.xpresso;

import java.util.ArrayList;
import java.util.Iterator;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.forms.Form;
import com.erclab.internal.xpresso.options.Option;
import com.erclab.internal.xpresso.reports.Report;
import com.erclab.internal.xpresso.security.User;

/**
 * @author Enrique Rodriguez.
 *
 */
public class OptionsFactory {

	protected static void prepareOptions(ArrayList options, String uniqueKeyValue) {
		if (options != null){
			for (Iterator iter = options.iterator(); iter.hasNext();) {
				// Replace uniqueKeyValue
				Option o = (Option)iter.next();
				if (o != null && uniqueKeyValue != null){
					if (o.getLink() != null){
						// TODO: Create a utility class that will replace uniqueKeyvalues to concentrate
						// all the logic of replacement in one single place
						o.setLink(o.getLink().replaceAll("-param:uniqueKeyValue-", uniqueKeyValue));
					}
				}				
			}
		}		
	}


	public static void loadReportOptions(Report theReport, User theUser) throws Exception{
		// TODO: check if the options were already loaded for this report
		Settings.getRepository().getDaoFactory().getOptionsDAO().loadReportOptions(theReport, theUser);
		
		if(theReport.getReportParameters() != null){
			prepareOptions(theReport.getOptions(), theReport.getReportParameters().getUniqueKeyValue());
		} else {
			prepareOptions(theReport.getOptions(), null);
		}
	}

	public static void loadFormOptions(Form theForm, User theUser) throws Exception{
		Settings.getRepository().getDaoFactory().getOptionsDAO().loadFormOptions(theForm, theUser);
		
		prepareOptions(theForm.getOptions(), theForm.getFormParameters().getUniqueKeyValue());
	}

}
